<template>
    <div id="AndroidContingencyPlanOperation">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="ruleForm.title" label="方案标题：" placeholder="请输入方案标题" label-width="6rem"
                    :rules="[{ required: true, message: '请输入方案标题' }]" />
                <van-field v-model="ruleForm.explain" label="方案说明：" placeholder="请输入方案说明" label-width="6rem" rows="2"
                    autosize type="textarea" :rules="[{ required: true, message: '请输入方案说明' }]" />
                <van-field v-model="ruleForm.createTime" is-link disabled name="datePicker" label="发布时间："
                    placeholder="点击选择时间" v-if="isType" />
                <van-cell>
                    <p>选择默认负责人：</p>
                    <el-transfer v-model="ruleForm.leaderUsers" style="text-align: left; display: inline-block" filterable
                        :titles="['所有人员', '默认负责人']" :button-texts="['取消', '添加']" :data="data">
                    </el-transfer>
                </van-cell>
                <van-cell>
                    <p>方案内容：</p>
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="min-height: 200px; overflow-y: hidden;" v-model="ruleForm.detail"
                        :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                </van-cell>

            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    {{ btnText }}
                </van-button>
            </div>
        </van-form>

        <van-overlay :show="loading">
            <div class="wrapper">
                <van-loading type="spinner" size="5vh" vertical color="#fff">加载中...</van-loading>
            </div>
        </van-overlay>
    </div>
</template>

<script setup>
import dateTimeSpan, { dateTimeSpanWebApi } from '@/utils/dateTime';
import { inject, reactive, ref, shallowRef } from 'vue';
import axios from '@/utils/axios';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRoute } from 'vue-router';
import { Dialog } from 'vant';

let nav = inject('nav');
nav.showLeft = true;
nav.textLeft = '返回';
nav.title = '应急预案详情';
nav.showRight = false;


function getToken() {
    try {
        var token = sessionStorage.getItem('token');
        if (sessionStorage.getItem('RYD_UserId') != null) {
            token += ";" + sessionStorage.getItem('RYD_UserId')
        }
        return token;
    } catch (error) {
        return null;
    }
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const mode = ref('simple')

const toolbarConfig = ref({})
toolbarConfig.value.excludeKeys = [
    'emotion',
]

const editorConfig = ref({
    placeholder: '请输入内容...', MENU_CONF: {}
})
editorConfig.value.MENU_CONF['uploadImage'] = {
    server: '/api/EditorUpImage',
    headers: {
        "X-Token": getToken()
    },
}
editorConfig.value.MENU_CONF['uploadVideo'] = {
    server: '/api/EditorUpImage',
    headers: {
        "X-Token": getToken()
    },
}
editorConfig.value.scroll = false
editorConfig.value.autoFocus = false

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
};

const loading = ref(false);


const route = useRoute();
const ContingencyPlanNo = route.query.ContingencyPlanNo;
const Type = route.query.Type;

const isType = ref(false);
var btnText = ref("确认添加");
let RYD_UserId = inject('RYD_UserId');

if (ContingencyPlanNo != null && Type != null) {
    loading.value = true;
    if (Type == 1) {
        btnText.value = "确认修改";
        nav.title = "修改应急方案";
    } else if (Type == 2) {
        btnText.value = "确认发布";
        nav.title = "发布应急方案";
        isType.value = true;
    }
}



const onSubmit = () => {
    loading.value = true;

    var leaderUsers = '';
    ruleForm.leaderUsers.forEach(item => {
        if (leaderUsers != '') {
            leaderUsers += ",";
        }
        leaderUsers += item;
    });



    if (ContingencyPlanNo != null && Type != null) {
        //发布
        if (Type == 2) {
            axios({
                method: 'post',
                url: '/api/PublishContingencyPlanTable',
                data: {
                    RYD_ContingencyPlanTitle: ruleForm.title,
                    RYD_ContingencyPlanExplain: ruleForm.explain,
                    RYD_ContingencyPlanDetail: ruleForm.detail,
                    RYD_LeaderUsers: leaderUsers,
                    RYD_CreateBy: RYD_UserId,
                    RYD_CreateTime: dateTimeSpanWebApi(ruleForm.createTime),
                    RYD_ContingencyPlanNo: ContingencyPlanNo
                }
            }).then(() => {
                loading.value = false;
                Dialog.alert({
                    message: '发布成功，已通知负责人',
                    title: "提示"
                });
            }).catch(err => {
                loading.value = false;
                Dialog.alert({
                    message: '失败:' + err,
                    title: "提示"
                });
            })
            return;
        }
        //修改
        else if (Type == 1) {
            axios({
                method: 'post',
                url: '/api/AddContingencyPlanTable',
                data: {
                    RYD_ContingencyPlanTitle: ruleForm.title,
                    RYD_ContingencyPlanExplain: ruleForm.explain,
                    RYD_ContingencyPlanDetail: ruleForm.detail,
                    RYD_DefaultUsers: leaderUsers,
                    RYD_CreateBy: RYD_UserId,
                    RYD_ContingencyPlanNo: ContingencyPlanNo
                }
            }).then(() => {
                loading.value = false;
                Dialog.alert({
                    message: '修改成功',
                    title: "提示"
                });
            }).catch(err => {
                loading.value = false;
                Dialog.alert({
                    message: '失败:' + err,
                    title: "提示"
                });
            })
            return;
        }
    }
    axios({
        method: 'post',
        url: '/api/AddContingencyPlanTable',
        data: {
            RYD_ContingencyPlanTitle: ruleForm.title,
            RYD_ContingencyPlanExplain: ruleForm.explain,
            RYD_ContingencyPlanDetail: ruleForm.detail,
            RYD_DefaultUsers: leaderUsers,
            RYD_CreateBy: RYD_UserId,
        }
    }).then(() => {
        loading.value = false;
        Dialog.alert({
            message: '添加成功',
            title: "提示"
        });
        ruleForm.title = '';
        ruleForm.explain = '';
        ruleForm.leaderUsers = [];
        ruleForm.detail = '';
    }).catch(err => {
        loading.value = false;
        Dialog.alert({
            message: '失败:' + err,
            title: "提示"
        });
    })
};

const ruleForm = reactive({
    title: '',
    explain: '',
    leaderUsers: [],
    detail: '',
    createTime: dateTimeSpan(Date.now())
})
const data = ref([])
axios({
    method: 'post',
    url: '/api/GetAllUser',
    data: {

    }
}).then(res => {
    res.forEach(item => {
        data.value.push({
            key: item.ryD_Id,
            label: item.ryD_RyderNo + " " + item.realName
        })
    });
})

if (ContingencyPlanNo != null) {
    axios({
        method: 'get',
        url: '/api/GetContingencyPlanTableInfo?ContingencyPlanNo=' + ContingencyPlanNo,
    }).then(res => {
        loading.value = false;
        ruleForm.detail = res.ryD_ContingencyPlanDetail;
        ruleForm.explain = res.ryD_ContingencyPlanExplain;
        ruleForm.title = res.ryD_ContingencyPlanTitle;
        ruleForm.leaderUsers = res.ryD_DefaultUsers.split(',');
    })
}

</script>

<style>
#AndroidContingencyPlanOperation .van-field {
    padding: 20px 20px;
}

#AndroidContingencyPlanOperation .el-transfer-panel {
    width: 100%;
}

#AndroidContingencyPlanOperation .el-transfer-panel .el-input {
    width: 80%;
}

#AndroidContingencyPlanOperation .el-transfer-panel .el-input .el-input__inner {
    font-size: 1rem;
    line-height: 2rem;
    border-radius: 0;
}


#AndroidContingencyPlanOperation .el-transfer__buttons {
    text-align: center;
    width: 100%;
    padding: 0;
    margin: 10px 0;
}
</style>